import "./index.scss";
import React, { useState, useEffect } from "react";
import {
  Button,
  Form,
  Input,
  Select,
  Table,
  Space,
  Modal,
  Radio,
  Alert,
  message,
} from "antd";
import { ExclamationCircleFilled } from "@ant-design/icons";
import axios from "../../../../utils/http.jsx";
import PageName from "../../../../components/PageName/index.jsx";
import { useNavigate } from "react-router-dom";
// 日期格式转换
import { parseTime } from "@/utils/date.jsx";
// , onCancel
const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
  const [addForm] = Form.useForm();
  const openAdd = () => {
    onCancel();
    addForm.resetFields();
  };
  return (
    <Modal
      forceRender
      // getContainer={false}
      open={open}
      title="添加红包"
      okText="确定"
      cancelText="取消"
      onCancel={openAdd}
      onOk={() => {
        addForm
          .validateFields()
          .then((values) => {
            addForm.resetFields();
            onCreate(values);
          })
          .catch((info) => {});
      }}
    >
      <Form
        form={addForm}
        name="form_in_modal"
        initialValues={{
          isShow: "显示",
        }}
        colon={false}
      >
        <Form.Item
          label="选择楼盘"
          style={{ width: "250px" }}
          name="floor"
          rules={[
            {
              required: true,
              message: "请选择楼盘！",
            },
          ]}
        >
          {/* defaultValue="全部" */}
          <Select placeholder="请选择">
            <Select.Option value="东亚尚品台湖">东亚尚品台湖</Select.Option>
            <Select.Option value="西山锦绣府">西山锦绣府</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item
          name="price"
          label="红包金额"
          rules={[
            {
              required: true,
              message: "请输入红包金额！",
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="num"
          label="红包数量"
          rules={[
            {
              required: true,
              message: "请输入红包数量！",
            },
          ]}
        >
          <Input type="textarea" />
        </Form.Item>
        <Form.Item name="isShow" label="是否显示">
          <Radio.Group>
            <Radio value="显示">显示</Radio>
            <Radio value="不显示">不显示</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
    </Modal>
  );
};
const CollectionCreateForm1 = ({
  editOpen,
  onCreate1,
  onCancel1,
  editInitial,
}) => {
  const [editForm] = Form.useForm();
  useEffect(() => {
    editForm.setFieldsValue(editInitial);
  }, [editInitial]);
  return (
    <Modal
      forceRender
      open={editOpen}
      title="编辑红包"
      okText="确定"
      cancelText="取消"
      onCancel={onCancel1}
      onOk={() => {
        editForm
          .validateFields()
          .then((values) => {
            editForm.resetFields();
            onCreate1(values);
          })
          .catch((info) => {});
      }}
    >
      <Form
        form={editForm}
        name="form_in_modal"
        initialValues={{
          isShow: "显示",
        }}
        colon={false}
      >
        <Form.Item
          label="选择楼盘"
          style={{ width: "250px" }}
          name="floor"
          rules={[
            {
              required: true,
              message: "请选择楼盘！",
            },
          ]}
        >
          {/* defaultValue="全部" */}
          <Select placeholder="请选择">
            <Select.Option value="东亚尚品台湖">东亚尚品台湖</Select.Option>
            <Select.Option value="西山锦绣府">西山锦绣府</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item
          name="price"
          label="红包金额"
          rules={[
            {
              required: true,
              message: "请输入红包金额！",
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="num"
          label="红包数量"
          rules={[
            {
              required: true,
              message: "请输入红包数量！",
            },
          ]}
        >
          <Input type="textarea" />
        </Form.Item>
        <Form.Item name="isShow" label="是否显示">
          <Radio.Group>
            <Radio value="显示">显示</Radio>
            <Radio value="不显示">不显示</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
    </Modal>
  );
};
const RedPacket = () => {
  // 时间转换
  const date = () => {};
  // 消息提示
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const success = () => {
    messageApi.open({
      type: "success",
      content: "添加成功！",
    });
  };
  // 删除模态框
  const { confirm } = Modal;
  // 获取全部数据
  useEffect(() => {
    getRed();
  }, []);
  //获取红包数据
  const getRed = () => {
    axios({
      url: "/red/getRed",
    })
      .then((res) => {
        setDataList(res.data);
      })
      .catch((err) => {});
  };
  // 搜索数据
  const [form] = Form.useForm();
  const [createFrom] = Form.useForm();

  // 搜索方法
  const searchBtn = (params) => {
    if (params.keywords == undefined) {
      params.keywords = "";
    }
    if (params.status == undefined) {
      params.status = "";
    }
    axios({
      url: "/red/getSingleRed",
      method: "get",
      params: {
        status: params.status,
        name: params.keywords,
      },
    })
      .then((res) => {
        setDataList(res.data);
      })
      .catch((err) => {});
  };
  // 清空
  const onClear = () => {
    form.resetFields();
    getRed();
  };
  // 表格数据
  const [dataList, setDataList] = useState([]);
  // const getPageContent = (page, pageSize) => {
  //   this.getData(page, pageSize);
  // };
  // 表格列
  const columns = [
    // {
    //   title: "编号", //表格列名
    //   dataIndex: "red_id", //该列对应数据字段
    //   key: "red_id", //该列唯一值
    //   align: "center",
    // },
    // 表格序号自增长
    {
      title: "序号",
      dataIndex: "index",
      align: "center",
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: "楼盘", //表格列名
      dataIndex: "floor_id", //该列对应数据字段
      key: "floor_id", //该列唯一值
      align: "center",
    },
    {
      title: "红包金额",
      dataIndex: "amount",
      key: "amount",
      align: "center",
    },
    {
      title: "红包总数",
      dataIndex: "red_total",
      key: "red_total",
      align: "center",
    },
    {
      title: "剩余数量",
      dataIndex: "num",
      key: "num",
      align: "center",
    },
    {
      title: "状态",
      dataIndex: "show_status",
      key: "show_status",
      align: "center",
    },
    {
      title: "发布者",
      dataIndex: "admin_id",
      key: "admin_id",
      align: "center",
    },
    {
      title: "发布时间",
      dataIndex: "time",
      key: "time",
      align: "center",
      render: (_, { time }) => {
        return parseTime(time, "{y}-{m}-{d} {h}:{i}:{s}");
      },
    },
    {
      title: "操作",
      align: "center",
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              editFrom(record);
            }}
          >
            编辑
          </a>
          <a
            onClick={() => {
              editorFrom(record);
            }}
          >
            查看
          </a>
          <a
            onClick={() => {
              deleteFrom(record);
            }}
          >
            删除
          </a>
        </Space>
      ),
    },
  ];
  // 添加
  const [open, setOpen] = useState(false);
  const onCreate = (values) => {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth();
    var day = date.getDay();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    if (month < 10) {
      month = "0" + month;
    }
    if (day < 10) {
      day = "0" + day;
    }
    var sqlTime =
      year +
      "-" +
      month +
      "-" +
      day +
      " " +
      hours +
      ":" +
      minutes +
      ":" +
      seconds;

    setOpen(false);
    axios({
      url: "/red/addRed",
      method: "post",
      data: {
        floor_id: values.floor,
        amount: values.price,
        red_total: values.num,
        show_status: values.isShow,
        admin_id: "admin",
        time: sqlTime,
      },
    })
      .then((res) => {
        if (res.code == 200) {
          success();
          setOpen(false);
          getRed();
        }
      })
      .catch((err) => {});
  };

  // 编辑
  const [editInitial, setEditInitial] = useState({});
  const [editOpen, setEditOpen] = useState(false);
  const [editId, setEditId] = useState();
  const editFrom = (record) => {
    let initialData = {
      floor: record.floor_id,
      price: record.amount,
      num: record.red_total,
      isShow: record.show_status,
    };
    setEditInitial(initialData);
    setEditId(record.red_id);
    setEditOpen(true);
  };
  // 确认编辑
  const onCreate1 = (values) => {
    // setEditOpen(false);
    axios({
      url: "/red/updateRed",
      method: "post",
      data: {
        red_id: editId,
        floor_id: values.floor,
        amount: values.price,
        red_total: values.num,
        show_status: values.isShow,
      },
    })
      .then((res) => {
        if (res.code == 200) {
          messageApi.open({
            type: "success",
            content: "修改成功！",
          });
          setEditOpen(false);
          getRed();
        }
      })
      .catch((err) => {});
  };
  // 查看
  const editorFrom = (record) => {
    navigate("/home/ViewRedPacket", { state: { id: record.red_id } });
  };
  //删除
  const deleteFrom = (record) => {
    confirm({
      title: "你确定要删除吗?",
      icon: <ExclamationCircleFilled />,
      okText: "Yes",
      okType: "danger",
      cancelText: "No",
      onOk() {
        axios({
          url: "/red/delRed",
          method: "post",
          data: {
            red_id: record.red_id,
          },
        })
          .then((res) => {
            if (res.code == 200) {
              messageApi.open({
                type: "success",
                content: "删除成功！",
              });
              getRed();
            }
          })
          .catch((err) => {});
      },
      onCancel() {},
    });
  };
  return (
    <div>
      {contextHolder}
      {/* <div className="RedPacket">
        <div className="RedPacketDiv">红包管理</div>
      </div> */}
      <PageName name="红包管理"></PageName>
      {/* 搜索栏 */}
      <div className="RedPacketFrom">
        <Form
          form={form}
          name="horizontal_login"
          layout="inline"
          onFinish={searchBtn}
          initialValues={{ status: "全部" }}
        >
          <Form.Item label="状态" style={{ width: "200px" }} name="status">
            {/*  defaultValue="全部" */}
            <Select placeholder="请选择">
              <Select.Option value="全部">全部</Select.Option>
              <Select.Option value="显示">显示</Select.Option>
              <Select.Option value="不显示">不显示</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="keywords" label="楼盘名称">
            <Input placeholder="请输入关键词查询" />
          </Form.Item>
          <Form.Item shouldUpdate>
            {() => (
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
            )}
          </Form.Item>
          <Form.Item>
            <Button onClick={onClear}>清空</Button>
          </Form.Item>
        </Form>
      </div>
      {/* 添加 */}
      <div className="RedPacketBtn">
        <Button
          type="primary"
          onClick={() => {
            setOpen(true);
          }}
        >
          添加
        </Button>
      </div>
      {/* 表格 */}
      <div>
        <Table
          className="RedPacketTable"
          columns={columns}
          pagination={{
            defaultCurrent: 1,
            defaultPageSize: 5,
            total: dataList.length,
            // pagination: {
            //   total: dataList.length,
            //   pageSize: 5,
            //   onChange: getPageContent,
            // },
            // //引入分页API
            // 只有一页的时候是否隐藏
            hideOnSinglePage: true,
          }}
          dataSource={dataList}
          rowKey={(record) => record.red_id}
        />
      </div>
      {/* 新增弹框 */}
      <div>
        <CollectionCreateForm
          open={open}
          onCreate={onCreate}
          // onCancel
          onCancel={() => {
            setOpen(false);
          }}
        />
      </div>
      {/* 编辑 */}
      <div>
        <CollectionCreateForm1
          editOpen={editOpen}
          onCreate1={onCreate1}
          onCancel1={() => {
            setEditOpen(false);
          }}
          editInitial={editInitial}
        />
      </div>
    </div>
  );
};

export default RedPacket;
